namespace.reg("roleManage.fun");
roleManage.fun = (function () {
    var initGrid = function (url) {
        var initTableData = function (currentPage, pageSize, parame) {
            if (baseJS.isEmpty(currentPage)) {
                currentPage = 1;
            }
            if (baseJS.isEmpty(pageSize)) {
                pageSize = 10;
            }
            var tableInitParam = {};
            var datas = {currentPage: currentPage, pageSize: pageSize};
            if (!baseJS.isEmpty(parame)) {
                $.extend(datas, parame);
            }
            baseJS.ajaxRequest({
                url:"/role/list",
                data:datas,
                success:function successCallback(reqData) {
                    tableInitParam = {
                        tableData: reqData.data,
                        total: reqData.number,
                        pageSize: 10,
                        currentPage: 1,
                    };
                },
                error:function errorCallback() {
                    baseJS.layerMsg("ajaxRequest请求出错");
                }
            });
            return tableInitParam;
        }

        var deleteTableData = function (id, callback) {
            $.ajax({
                url: "/backstage/deleteUser",
                dataType: "json",
                async: false,
                data: {id: id},
                type: "post",
                success: function (reqData) {
                    if (callback != null && typeof(callback) == "function") {
                        callback(reqData);
                    } else {
                        if (reqData.status) {
                            baseJS.layerMsg(reqData.msg);
                        }
                    }
                },
                error: function () {
                    baseJS.layerMsg("删除出错");
                }
            });
        };
        var app = new Vue({
            data:function() {
                var reqIniData = initTableData(1, 10);
                return {
                    item : null,
                    type : "add",
                    total: reqIniData.total,
                    pageSize: reqIniData.pageSize,
                    currentPage: reqIniData.currentPage,
                    selectRow: [],
                    layerIndex: '',
                    loadedData:function(currentPage, pageSize, parame) {
                        var pageData = initTableData(currentPage, pageSize, parame);
                        this.pageSize = pageData.pageSize;
                        this.total = pageData.total;
                        this.tableData = pageData.tableData;
                    },
                    columns: [
                        {
                            type: 'selection',
                            width: 60,
                            align: 'center'
                        },
                        {
                            title: '角色ID',
                            key: 'id'
                        },
                        {
                            title: '角色名称',
                            key: 'roleName'
                        },
                        {
                            title: '操作',
                            key: 'action',
                            width: 150,
                            align: 'center',
                            render: function(h, params) {
                                return h('div', [
                                    h('Button', {
                                        props: {
                                            type: 'primary',
                                            size: 'small'
                                        },
                                        style: {
                                            marginRight: '5px'
                                        },
                                        on: {
                                            click: function(){
                                                app.editRoleFun(params.index,params.row);
                                            }
                                        }
                                    }, '编辑'),
                                    h('Button', {
                                        props: {
                                            type: 'error',
                                            size: 'small'
                                        },
                                        on: {
                                            click: function(){
                                                app.distributionQX(params.index,params.row);
                                            }
                                        }
                                    }, '分配权限')
                                ]);
                            }
                        }
                    ],
                    tableData: reqIniData.tableData
                }
            },
            methods: {
                handleRowChange(selection){
                    this.selectRow = selection;
                },
                onPageSizeChange:function (value) {
                    this.loadedData(1,value);
                },
                distributionQX: function(index,row){
                    baseJS.baseLayerOpen({
                        url:"/backstage/roleManage/roleLabel"
                        ,title:"分配权限"
                        ,type:1
                        ,width:400
                        ,height:400
                        ,maxmin:false
                        ,successCallbackLayerOpenFun:function (val,index) {
                            roleManage.fun.initMenu(row);
                            vueGridApp.item = row;
                            vueGridApp.layerIndex = index;
                        }
                    });
                },
                delete:function(index) {
                    baseJS.layerOpenAle("确定要删除吗？", "温馨提示", function () {
                        deleteTableData(vueGridApp.tableData[index].id,function callback(reqData) {
                            if( reqData.status ){
                                vueGridApp.tableData.splice(index, 1);
                                if(vueGridApp.tableData.length == 0){
                                    vueGridApp.loadedData(vueGridApp.currentPage - 1, vueGridApp.pageSize);
                                }
                                baseJS.layerMsg(reqData.msg);
                            }
                        });
                    });
                },
                deleteBatch:function(ev) {
                    var vueThis = this;
                    const selectRow = this.selectRow;
                    if (selectRow.length == 0) {
                        baseJS.layerMsg("请选择要删除的数据");
                        return true;
                    } else {
                        baseJS.layerOpenAle("确定要删除吗？", "温馨提示", function () {
                            var itemIds = [];
                            for (var index in selectRow) {
                                itemIds.push(selectRow[index].id);
                            }
                            baseJS.ajaxRequest({
                                url:"/role/deleteBatch",
                                data:{itemIds: itemIds},
                                success:function successCallback(data) {
                                    if (!baseJS.isEmpty(data) && data.status == 1) {
                                        baseJS.layerMsg(data.msg, function callback() {
                                            vueThis.loadedData(vueThis.currentPage, vueThis.pageSize);
                                        });
                                    } else {
                                        baseJS.layerMsg("删除失败！");
                                    }
                                },
                                error:function errorCallback() {
                                    baseJS.layerMsg("删除失败！");
                                }
                            });
                        });
                    }
                },
                addButt:function () {
                    var vueThis = this;
                    this.type = "add";
                    baseJS.baseLayerOpen({
                        url:"/backstage/roleManage/addRole"
                        ,title:"新增角色"
                        ,type:1
                        ,width:600
                        ,height:400
                        ,maxmin:false
                        ,successCallbackLayerOpenFun:function (val, indexs) {
                            vueGridApp.layerIndex = indexs;
                            roleManage.fun.initAddForm(indexs,function(){
                                vueThis.loadedData(1,this.pageSize);
                            });
                        }
                    });
                },
                editRoleFun:function (index,row) {
                    var vueThis = this;
                    this.item = row;
                    this.type = "edit";
                    baseJS.baseLayerOpen({
                        url:"/backstage/roleManage/addRole"
                        ,title:"修改角色"
                        ,type:1
                        ,width:600
                        ,height:400
                        ,maxmin:false
                        ,successCallbackLayerOpenFun:function (val,indexs) {
                            roleManage.fun.initAddForm(indexs,function(){
                                vueThis.loadedData(1,this.pageSize);
                            });
                        }
                    });
                },
                pageNext:function (currentPage) {
                    this.loadedData(currentPage, this.pageSize);
                }
            }
        });
        vueGridApp = app;
        app.$mount('#app')
    }
    var initAddForm = function (index,formCallback) {
        var initFormMain = {
            data:function(){
                var roleName = "";
                if( vueGridApp.type == "edit"){
                    roleName = vueGridApp.item.roleName;
                }
                var role = {
                    roleName:roleName
                }
                return {
                    role:role,
                    loading:false,
                    rules:{
                        roleName: [
                            { required: true, message: '请输入角色名称', trigger: 'blur' },
                            { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                        ]
                    }
                }
            },

            methods: {
                onSubmit:function () {
                    var data = {
                        roleName:this.role.roleName
                    };
                    var zTree = $.fn.zTree.getZTreeObj("treeBox"),
                        checkNode= zTree.getCheckedNodes(true);
                    var ids = new Array();
                    for(var i=0;i<checkNode.length;i++){
                        ids.push(checkNode[i].id);
                    }
                    data.mId = ids.join(",");
                    var url = "/role/addRole";
                    if( vueGridApp.type == "edit" ){
                        url = "/role/updateRole";
                        data.id = vueGridApp.item.id;
                    }
                    baseJS.ajaxRequest({
                        url:url,
                        data:data,
                        dataType : "json",
                        success:function successCallback(data){
                            //  data = JSON.parse(data);
                            if(!baseJS.isEmpty(data) && data.status == 1){
                                baseJS.layerMsg("操作成功！",function callback() {
                                    layer.close(index);
                                    // vueGridApp.loadedData(vueGridApp.currentPage,vueGridApp.pageSize);
                                    if ( formCallback!= null && typeof(formCallback) == "function" ){
                                        formCallback();
                                    }
                                });
                            }
                        }
                    });
                },
                onSubmitValidate:function (name) {
                    this.$refs[name].validate((valid) => {
                        if (valid) {
                            this.onSubmit();
                        }
                    });
                }
            }
        }
        var initFormCtor = Vue.extend(initFormMain)
        new initFormCtor().$mount('#initFormApp')
        roleManage.fun.initMenu(vueGridApp.item);
    }

    var getRoleList = function () {
        var reqData = null;
        baseJS.ajaxRequest({
            url:"/role/getRoleList",
            success:function success(data) {
                reqData = data.data;
            },
            error:function error() {
                baseJS.layerMsg("获取角色失败");
            }
        });
        return reqData;
    }
    var initMenu = function (item) {
        var setting = {
            check: {
                enable: true,
                chkStyle: "checkbox",
                chkboxType: { "Y": "p", "N": "s" }
            },
            data: {
                simpleData: {
                    enable: true,
                    idKey: "id",
                    pIdKey: "parentId",
                }
            }
        };
        var id = null;
        if( !baseJS.isEmpty(item)){
            id = item.id
        }
        $.ajax({
            url:"/menu/getMenuByRoleId",
            type:'post',
            async:false,
            data:{id:id},
            dataType:'json',
            success:function(data){
                $.fn.zTree.init($("#treeBox"), setting, data);
                var zTree = $.fn.zTree.getZTreeObj("treeBox");
                zTree.expandAll(true);
            },
            error:function(xhr,textStatus) {
                baseJS.layerMsg("初始化失败！");
            }
        })
    }
    //保存权限的选择
    var saveRoleMenu = function(item,callback) {
        var zTree = $.fn.zTree.getZTreeObj("treeBox"),
            checkNode= zTree.getCheckedNodes(true);
        var ids = new Array();
        for(var i = 0; i < checkNode.length; i++){
            ids.push(checkNode[i].id);
        }
        const data = baseJS.ajaxRequestSsyncFalse(window.location.protocol+"//" + window.location.host+"/roleMenu/saveRoleMenu", {roleId:item.id,mId:ids});
        if(!baseJS.isEmpty(data) && data.status == 1){
            baseJS.layerMsg("提交成功！",function () {
                callback(1);
            });
        }else{
            baseJS.layerMsg("提交失败！",function () {
                callback(0);
            });
        }
        /*baseJS.ajaxRequest(window.location.protocol+"//" + window.location.host+"/roleMenu/saveRoleMenu",
            "json",{roleId:item.id,mId:ids.join(",")},
            function successCallback(data){
            baseJS.layerMsg("提交成功！",function callback() {
                layer.close(index);
            });
        },function errorCallback() {
            baseJS.layerMsg("提交失败！");
        });*/
    }
    return {
        initGrid: initGrid,
        initAddForm:initAddForm,
        initMenu:initMenu,
        saveRoleMenu:saveRoleMenu
    }
})();

